package com.indusfo.spc.service.impl;


import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.*;
import com.indusfo.spc.pojo.Datadict;
import com.indusfo.spc.pojo.ProductLine;
import com.indusfo.spc.pojo.Station;
import com.indusfo.spc.service.StationService;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @author chenm
 * @create 2019-07-13 14:34
 */
@Service("stationService")
public class StationServiceImpl implements StationService {

    private  static  final Logger logger = LoggerFactory.getLogger(StationServiceImpl.class);

    @Resource
    private StationMapper stationMapper;

    @Resource
    private ProductLineMapper productLineMapper;

    @Resource
    private DatadictMapper tdatadictMapper;

    @Resource
    private ProListMapper proListMapper;
    @Resource
    private UploadMapper uploadMapper;
    /**
     * 新增
     * @param station
     * @return
     */
    @Override
    public JSONObject insertStation(Station station) {
        try {
            if(station.getStaId() != null) {
                throw new ParamsErrorException("新增操作不能选择工位");
            }
            //获取到车间ID
            //通过产品线获取
            Integer productionLineId = station.getProductionLineId();
            List<ProductLine> productLine = productLineMapper.getProductLine(productionLineId);
            Integer workshopId = productLine.get(0).getWorkshopId();
            station.setWorkshopId(workshopId);
            checkParam(station);
            checkNoRepate(station);

            int row = stationMapper.insertSelective(station);
            if(row == 0) {
                throw new ModifyFailedException("数据新增失败！");
            }
            return JSONObject.oK("新增成功！");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }


    /**
     * 删除
     * @param
     * @return
     */
    @Override
    public JSONObject delStation(Integer[] staIds, Integer dataState) {
        try {
            if( dataState == null) {
                throw new ParamsErrorException("数据状态不能为空");
            }else if( dataState != 1 &&  dataState != 2 &&  dataState != 3) {
                throw new ParamsErrorException("数据状态错误");
            }
            if (staIds == null) {
                throw new ParamsErrorException("请选择要删除的工位");
            }
            // 执行存储过程
            int row = stationMapper.delStation(staIds,  dataState);
            String msg = "";
            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch ( dataState) {
                    case 1:
                        throw new ModifyFailedException("启用失败");
                    case 2:
                        throw new ModifyFailedException("删除失败");
                    case 3:
                        throw new ModifyFailedException("停用失败");
                    default:
                }
            } else {
                switch ( dataState) {
                    case 1:
                        msg = "启用成功";break;
                    case 2:
                        msg = "删除成功";break;
                    case 3:
                        msg = "停用成功";break;
                    default:
                }
            }
            int i = proListMapper.updateProListByStaId(staIds, dataState);
            return JSONObject.oK(msg);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }


    /**
     * 修改
     * @param station
     * @return
     */
    @Override
    public JSONObject updateStation(Station station) {
        try {
            if(station.getStaId() == null) {
                throw new ParamsErrorException("请选择要修改的工位资料");
            }
            //通过产品线获取
            Integer productionLineId = station.getProductionLineId();
            List<ProductLine> productLine = productLineMapper.getProductLine(productionLineId);
            if(productLine.isEmpty()){
                throw new ModifyFailedException("数据不能为空");
            }
            Integer workshopId = productLine.get(0).getWorkshopId();
            station.setWorkshopId(workshopId);
            checkParam(station);
            checkNoRepate(station);
            int	row = stationMapper.updateByPrimaryKeySelective(station);

            if(row == 0) {
                throw new ModifyFailedException("数据更新失败！");
            }
            return JSONObject.oK("更新成功！");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }


    /**
     * 查询
     * @param station
     * @return
     */
    @Override
    public JSONObject queryStation(Station station) {
        List<Station> liststStations = null;
        try {
            Integer pagesize = station.getPagesize();
            Integer pageindex = station.getPageindex();
            if(pagesize != null && pageindex != null) {
                station.setIncept(pagesize*(pageindex - 1));
            }
            /*Integer lProductLineId = station.getStaId();
            if(lProductLineId != null) {  //如果有id,则查询单个产线信息
                liststStations = stationMapper.getStation(lProductLineId);
            } else{  //查询多个sop管理信息

            }*/
            liststStations = stationMapper.listStation(station);
            if (liststStations.isEmpty()) {
                return JSONObject.oK("没有产线相关数据", liststStations, 0);
            }
            //查询分页总记录数
            int count = stationMapper.countStation(station);
            return JSONObject.oK("查询成功", liststStations, count);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }


    /**
     * 根据编码查重
     * @param station
     * @return
     */
    @Override
    public Station getByStationCode(String staCode, Integer staId) {
        // TODO Auto-generated method stub
        return stationMapper.getByStationCode(staCode,staId);
    }


    /**
     * 根据产线查询工位集合
     * @param station
     * @return
     */
    @Override
    public List<Station> getByProductionLineId(Integer productionLineId) {
        // TODO Auto-generated method stub
        return stationMapper.getByProductionLineId(productionLineId);
    }

    /**
     * 根据车间查询工位集合
     * @param station
     * @return
     */
    @Override
    public List<Station> getByWorkshopId(Integer workShopId) {
        // TODO Auto-generated method stub
        return stationMapper.getByWorkshopId(workShopId);
    }


    /**
     * 根据工序查询工位集合
     * @param station
     * @return
     */
    @Override
    public List<Station> getByProId(Integer proId) {
        // TODO Auto-generated method stub
        return stationMapper.getByProId(proId);
    }




    /**
     * 信息验证
     * @param station
     * @return
     */
    private void checkParam(Station station){
        if(StringUtils.isEmpty(station.getStaCode())){
            throw new ParamsErrorException("工位编码不能为空");
        }
        if(station.getStaCode().length()>50){
            throw new ParamsErrorException("工位编码长度不能大于50");
        }
        if(getByStationCode(station.getStaCode(),station.getStaId()) != null){
            throw new ParamsErrorException("工位编码已存在");
        }
        if(StringUtils.isEmpty(station.getStaName())){
            throw new ParamsErrorException("工位名称不能为空");
        }
        if(station.getStaType()==null){
            throw new ParamsErrorException("工位类型不能为空");
        }
        if(station.getStaName().length()>50){
            throw new ParamsErrorException("工位名称的长度不能大于50");
        }
        /*if(station.getWorkshopId() == null){
            throw new ParamsErrorException("请选择所属车间");
        }*/
        if(station.getProductionLineId() == null){
            throw new ParamsErrorException("请选择所属产线");
        }
        if(station.getRemark().length()>100){
            throw new ParamsErrorException("备注说明的长度不能大于100");
        }
    }
    /**
     *根据名称去重
     */
    private void checkNoRepate(Station station){
        int count = stationMapper.selectByStaName(station);
        if(count>0){
            throw new ParamsErrorException("工位名称已存在");
        }
    }
    /**
     * @author: louk
     * @Description: 删除工序信息下的工位
     * @date: 2019/9/5 14:27
     *
     */

    @Override
    public JSONObject delStationByPro(Long[] staIds) {

        try{

            if (staIds==null) {
                throw new ParamsErrorException("请选择要删除的工位");
            }
            int row = stationMapper.deleteStationByPro(staIds);
            if(row==0){
                throw new ParamsErrorException("工位删除失败");
            }
            return JSONObject.oK("删除成功！");

        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public String checkExcelContent(Station station){
        //判断当前行内容是否为空/不存在
        if(StringUtils.isBlank(station.getStaCode()) && StringUtils.isBlank(station.getStaName()) && StringUtils.isBlank(station.getStaTypeName()) &&
                StringUtils.isBlank(station.getRemark()) && StringUtils.isBlank(station.getProductionLineName())){
            return "该行数据为空(原因:清空行内容时未清空彻底/未输入)";
        }
        if(StringUtils.isEmpty(station.getStaCode())){
            return "工位编码为空";
        }
        if(station.getStaCode().length()>50){
            return "工位编码长度大于50";
        }
        if(stationMapper.checkNoRepeatStaCode(station)>0){
            return "工位编码已存在";
        }
        if(StringUtils.isEmpty(station.getStaName())){
            return "工位名称为空";
        }
        if(stationMapper.checkNoRepeatStaName(station)>0){
            return "工位名称已存在";
        }
        if(station.getStaTypeName()==null){
            return "工位类型为空";
        }
        Map<String, Datadict> tdatadictMap = uploadMapper.queryType(101039);
        if(!tdatadictMap.containsKey(station.getStaTypeName())){
            return "工位类型输入错误/不规范";
        }else{
            Datadict tdatadict = tdatadictMap.get(station.getStaTypeName());
            station.setStaType(tdatadict.getItemId());
        }
        if(station.getStaName().length()>50){
            return "工位名称的长度不能大于50";
        }
        if(StringUtils.isBlank(station.getProductionLineName())){
            return "所属产线为空";
        }
        Map<String, ProductLine> productLineMap = uploadMapper.queryProductionLine();
        if(!productLineMap.containsKey(station.getProductionLineName())){
            return "所属产线输入错误/不规范";
        }else{
            station.setProductionLineId(productLineMap.get(station.getProductionLineName()).getLProductionLineId());
            //获取到车间ID
            //通过产品线获取
            Integer productionLineId = station.getProductionLineId();
            List<ProductLine> productLine = productLineMapper.getProductLine(productionLineId);
            Integer workshopId = productLine.get(0).getWorkshopId();
            station.setWorkshopId(workshopId);
        }
        if(station.getRemark()!=null && station.getRemark().length()>100){
            return "备注说明的长度不能大于100";
        }
        return null;
    }

}
